from mathutils import Vector
from starfield import NameGenerator
from starfield import Moon
from starfield.Entity import Entity
import starfield
import random
import math


class Planet(Entity):
	def __init__ (self, name, location = Vector([0.0, 0.0, 0.0])):
	
		Entity.__init__(self, location)
		
		self.mass = random.randint(1500, 4000)
		self.star = -1
		self.role = "planet"

		self.game_object = 0
		
		try:
			self.id = starfield.GameMaster.get_new_id()
		except:
			pass
			
	def update(self, time):
		Entity.update(self, time)
		if self.game_object != 0:
			self.game_object.position = self.location
			
	### Arguments for planet generation
	# seed = numer assigned to python's random number generator
	# scale = minimum distance between stars, in blender units
	def generateMoons(self, seed, scale = 1.0):
		system = {}
		self.moonlist = []
		#random.seed(seed)
		
		size_min = 0
		size_max = 8
		size = random.randint(size_min, size_max)
		self.size = size
		
		minDistance = 30 * scale
		spacing = 10 * scale
		spaces = list(range(size_max))
		
		def randRotate(radius):
			angle = random.random() * 2 * math.pi
			x = radius * math.cos(angle)
			y = radius * math.sin(angle)
			z = 0.0
			return Vector([x, y, z])
		
		# Potential to have opposite rotation as it's parent (20%)
		def addRotation():
			
			planetRot = self.rotation
			x = random.random()
			
			if x > .2 :
				return planetRot
			
			elif planetRot == 1:
				return -1
			
			else:
				return 1
		
		for i in range(size):
			# generate a name
			name = starfield.galaxy.namer.getName()
			
			# pick an open spot
			space = random.choice(spaces)
			spaces.remove(space)
			
			# what is the radius ?
			radius = space * spacing + minDistance
			
			# add some rotation, and finally, add that on to the planetss location
			location = randRotate(radius) + self.location
			
			# let's make the moon
			moon = Moon.Moon(name, location)
			
			# let's give it some rotation !
			moon.rotation = addRotation()
			
			# Who's yo daddy?
			moon.planet = self
			
			# add the moon to the system dictionary
			system[name] = moon
			
			self.moonlist.append(moon)
			
		self.moons = system
		return system
		